import { mapGetters } from 'vuex'
import { conversation, conversationStop, getDocumentSummary, getDocumentSuggestion, getConversationMessages } from '@/api/chat'
import { getAgentDetailApi } from '@/api/agent'
import { getSnowflakeId, awaitNextick, isSensitiveCode, formatSumarizeType } from '@/utils/index'
import queueReponseText from '@/utils/stream-reader-markdown'
import PsMessage from '@/components/message/index'
import PsMessageBox from '@/components/message-box/index'
import { getLocalStorage, setLocalStorage } from '@/utils/storage'
import { invokeAPi } from '@/xz-fn'
import {
  getMessageList,
  getSendParams,
  getPrevValidateCode,
  getResendMessageList,
  combnePrompMenuWithMessage
} from '@/utils/chat'

// import { report } from '@/directives/report'

export default {
  computed: {
    ...mapGetters(['chatStore', 'hasLogin', 'userInfo'])
  },
  provide () {
    return {
      setHistoryMessage: this.setHistoryMessage, // 传入一个方法
      stopMessage: this.stopMessage,
      resendMessage: this.resendMessage,
      reEditMessage: this.reEditMessage,
      switchMessage: this.switchMessage,
      likeStatus: this.likeStatus,
      detectIsLogin: this.detectIsLogin,
      resetNode: this.resetNode,
      sendMessage: this.sendMessage,
      clickAgentItem: this.clickAgentItem,
      setIsAgentNew: this.setIsAgentNew,
      addNewMessage: this.addNewMessage
    }
  },
  data () {
    return {
      rootNode: null,
      curNode: null,
      isAgentNew: false
    }
  },
  watch: {
    'hasLogin' (val) {
      if (!val) {
        this.addNewMessage()
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      const isANew = getLocalStorage('isAgentNew')
      this.isAgentNew = !isANew || false
      setLocalStorage('isAgentNew', true)
    }, 100)
  },
  methods: {
    setIsAgentNew () {
      this.isAgentNew = false
      setLocalStorage('isAgentNew', true)
    },
    // 检测登录
    detectIsLogin () {
      if (this.hasLogin) return true
      PsMessage({ message: '请您登录后再使用' })
      setTimeout(() => {
        this.$gotoLogin()
      }, 1000)
      return false
    },
    // 检测权益是否充足
    detechRightsRest () {
      let rest = 0
      let curModel = null
      if (process.env.VUE_APP_BUY_TYPE === 'right') {
        // 文档总结对话
        if (this.chatStore.docSummarize.status) {
          const summary_right_id = ({
            'xz': '10015',
            'dll': '80515'
          })[process.env.VUE_APP_NAME]

          rest = this.userInfo.userRights.find((v) => v.right_id === summary_right_id)?.rest_limit || 0
        } else {
          curModel = this.chatStore.currentModel
          rest = this.userInfo.userRights.find((v) => v.right_id === curModel?.right_id)?.rest_limit || 0
        }
        if (rest > 0) return true
      } else if (['token', 'energy'].includes(process.env.VUE_APP_BUY_TYPE)) {
        rest = this.userInfo.userToken
        const minCount = process.env.VUE_APP_MIN_COUNT // 最小数量
        if (rest >= minCount) return true
      }
      this.toastErrors(1008, curModel)
      return false
    },
    isDocSummarize () {
      return this.chatStore.docSummarize.status !== ''
    },
    // function isLinkSummarize () {
    //   return chatStore.docSummarize.type === 'link'
    // }
    getCurrentModel () {
      return this.isDocSummarize() ? this.chatStore.currentDocumentModel : this.chatStore.currentModel
    },
    setStatus (status, errorCode) {
    // eslint-disable-next-line sonarjs/no-duplicate-string
      this.$store.dispatch('chat/setChatStore', { status, errorCode: errorCode && errorCode !== 200 ? errorCode : null })
      if (this.curNode) {
        this.curNode.status = status
      }
    },

    addUserItem (item) {
      const node = {
        ...item,
        root: item.parent_message_id === '',
        next: null,
        prev: null,
        target: item,
        brothers: [item.message_id]
      }
      if (this.rootNode === null) {
        this.rootNode = node
        this.curNode = this.rootNode
      } else {
        node.prev = this.curNode
        if (this.curNode) this.curNode.next = node
        this.curNode = this.curNode?.next
      }
      // eslint-disable-next-line sonarjs/no-duplicate-string
      this.$store.dispatch('chat/setToCacheItem', this.curNode)
    },
    _getCurrentModel () {
      if (this.chatStore.docSummarize?.document?.document_id) return this.chatStore.docSummarize?.documentModelName
      return this.chatStore.currentModel?.name
    },

    addServerItem (messageId, business) {
      const node = {
        root: false,
        next: null,
        prev: null,
        message_id: '',
        parent_message_id: messageId,
        role: 'assistant',
        target: null,
        brothers: [],
        renderIndex: 0,
        renderContent: [],
        model: this._getCurrentModel(),
        // type: this.currentModel.type,
        status: 'wait',
        like_status: 'none',
        observation: {},
        tool: '',
        business
      }
      node.prev = this.curNode
      if (this.curNode) this.curNode.next = node
      this.curNode = this.curNode?.next
    },

    likeStatus (id, status) {
      let cur = this.rootNode
      while (cur !== null) {
        if (cur.message_id === id) {
          cur.like_status = status
          break
        } else {
          cur = cur.next
        }
      }
    },

    swtichMessage (node, index) {
      const self = this
      const prev = node.prev
      this.$store.dispatch('chat/getToCacheItem', {
        val: node.brothers[index],
        callback: function (next) {
          next.prev = prev
          prev.next = next
          next.renderIndex = index
          self.curNode = self.findeLastNode(next)
        }
      })
    },

    findeLastNode (node) {
      let cur = node
      while (cur) {
        if (!cur.next) return cur
        cur = cur.next
      }
      return null
    },
    popListChain () {
      const prev = this.curNode?.prev || null
      const old = this.curNode
      prev.next = null
      this.curNode = prev
      return old
    },

    // eslint-disable-next-line sonarjs/cognitive-complexity
    toastErrors (errorCode, model) {
      if (isSensitiveCode(errorCode)) return
      this.updateUserToken()
      if (errorCode === 1008) {
        if (process.env.VUE_APP_BUY_TYPE === 'energy') {
          if (!this.userInfo.is_member) {
            invokeAPi('HtmlClickReport', { ReportID: 7701 })
            // eslint-disable-next-line sonarjs/no-duplicate-string
            this.$store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，升级会员/购买加量包释放全能生产力吧！', eid: 8501 })
            return
          }
          invokeAPi('HtmlClickReport', { ReportID: 7705 })
          this.$store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，购买能量包释放全能生产力吧！<span class="vip-color">会员优享购买折扣哦！</span>' })
          return
        }
        if (process.env.VUE_APP_BUY_TYPE === 'token') {
          // eslint-disable-next-line
          this.$store.dispatch('system/setVipGuide', { status: true, title: '您的token余额不足，补充token释放全能生产力吧！' })
          return
        }
        if (!this.userInfo.is_member) {
          invokeAPi('HtmlClickReport', { ReportID: 7701 })
          this.$store.dispatch('system/setVipGuide', { status: true, title: '您的权益余额不足，升级会员释放全能生产力吧！', eid: 8501 })
          return
        }
        invokeAPi('HtmlClickReport', { ReportID: 7705 })
        PsMessageBox({
          message: `尊敬的VIP，您本月该功能权益次数已用完，您可以于次月购买日起再使用`,
          title: '权益提示',
          confirmButtonText: '知道了',
          showCancelButton: false,
          width: 312,
          confirmButtonClass: 'btn__primary_vip',
          beforeClose: (action, instance, done) => {
            done()
          }
        })
        return
      }
      if (errorCode === 4002) {
        PsMessageBox(
          {
            message: `尊敬的VIP，您本月${model?.name?.toUpperCase() || '模型'}权益次数已用完，您可以于次月购买日起再使用`,
            title: '权益提示',
            confirmButtonText: '知道了',
            showCancelButton: false,
            width: 312,
            confirmButtonClass: 'btn__primary_vip',
            beforeClose: (action, instance, done) => {
              done()
            }
          }
        )
        return
      }
      if (errorCode === 4003) {
        if (process.env.VUE_APP_BUY_TYPE === 'energy') {
          if (!this.userInfo.is_member) {
            invokeAPi('HtmlClickReport', { ReportID: 7701 })
            this.$store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，升级会员/购买加量包释放全能生产力吧！', eid: 8501 })
            return
          }
          invokeAPi('HtmlClickReport', { ReportID: 7705 })
          this.$store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，购买能量包释放全能生产力吧！<span class="vip-color">会员优享购买折扣哦！</span>' })
          return
        }
        const title = this.isDocSummarize()
          ? '文档总结对话'
          : this.chatStore.currentModel.right_cat_name || '对话功能'
        this.$store.dispatch('system/setVipGuide', { status: true, title: `您的【${title}】已达到免费上限，升级VIP享AI特权，高效助力办公浏览查询！` })
        return
      }
      if ([1013, 1028].includes(errorCode)) {
        PsMessageBox({
          message: `当前模型为VIP专享，马上开通享更多特权吧！`,
          title: '权益提示',
          confirmButtonText: '开通VIP',
          cancelButtonText: '知道了',
          width: 312,
          // eslint-disable-next-line sonarjs/no-identical-functions
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.$gotoMember()
            }
            done()
          }
        })
        return
      }
      if ([1009].includes(errorCode)) {
        return
      }
      const errorCodes = {
        1001: '请切换其它AI模型',
        1002: '请切换其它AI模型',
        1008: '当前权益受限，请先升级会员',
        4001: '当前免费用户权益已用完，请先升级为会员',
        4002: `尊敬的VIP，您本月${model?.name?.toUpperCase() || '模型'}权益次数已用完，请于次月购买日（含）起再使用`,
        4003: '当前免费用户权益已用完，请先升级为会员'
      }
      // eslint-disable-next-line sonarjs/no-duplicate-string
      const msg = errorCodes[errorCode || -1] || '请稍候重试或联系客服'
      PsMessage({ message: msg })
    },
    /**
   * 判断是否正在会话中
   * @returns boolean
   */
    detectIsChating () {
      if (this.chatStore.docSummarize.status === 'wait' && this.chatStore.docSummarize.type !== 'link') {
        PsMessage({ message: '请先上传文档再开始对话哦' })
        return true
      }
      const status = this.chatStore.status || this.chatStore.docSummarize.status
      if (['wait', 'chating', 'analysis'].includes(status)) {
        const message = '正在生成，请稍等！'
        PsMessage({ message })
        return true
      }
      return false
    },

    /**
   * 发送会话信息
   */
    // eslint-disable-next-line sonarjs/cognitive-complexity
    async sendMessage (input, promptMenu, options = {}) {
      if (this.detectIsChating()) return
      if (this.chatStore.docSummarize.status === 'error') {
        this.toastErrors(this.chatStore.docSummarize.code)
        return
      }
      this.$store.dispatch('chat/setChatStore', { chatInput: '' })
      if (this.isDocSummarize()) {
      // report(isLinkSummarize() ? 250 : 241)
      }
      if (this.curNode?.role === 'clipbord') {
        this.removeClipbordTipsNode()
      }
      if (!this.detechRightsRest()) return
      this.$store.dispatch('agent/setAgentShow', false)
      let conversionId = this.chatStore.conversionId
      const messageId = getSnowflakeId()

      const messages = options.noHistory ? [] : getMessageList(this.rootNode)
      const isNewConverSation = !conversionId
      if (!conversionId) {
        conversionId = getSnowflakeId()
      }
      this.$store.dispatch('chat/setChatStore', { conversionId })

      let message = {
        role: 'user',
        content: input,
        message_id: messageId,
        message_type: '',
        parent_message_id: getPrevValidateCode(this.curNode, 'assistant')?.message_id || ''
      }
      if (options.business) {
        message.business = options.business
      }
      message = combnePrompMenuWithMessage(message, promptMenu)
      messages.push(message)
      const docSummarize = this.chatStore.docSummarize
      const params = getSendParams(
        messages,
        this.getCurrentModel(),
        conversionId,
        docSummarize.document?.knowledge_id
      )
      params.enable_tool_serper = this.chatStore.onlineSwitch
      if (options.app_assistant_id) { // 外部传的优先
        params.app_assistant_id = options.app_assistant_id
      } else if (this.chatStore.agent) {
        this.$xz('HtmlClickReport', { ReportID: 7621 })
        params.app_assistant_id = this.chatStore.agent.id
      }

      // 提问
      this.addUserItem(message)
      this.$store.dispatch('chat/setChatStore', { newSession: this.chatStore.newSession + 1, isChating: true })
      this.setStatus('wait')
      this.addServerItem(message.message_id, params.app_assistant_id === 489 ? '1' : '')
      this.$store.dispatch('chat/setChatStore', { newSession: this.chatStore.newSession + 1 })
      this.$xz('HtmlClickReport', { ReportID: 7615 })
      this.$xz('HtmlEventSceneReport', { ReportID: 7615, data: { scene: 7615, user_id: this.userInfo.userid, param1: this.userInfo.is_member ? 1 : 0 } })
      this.scrollToAnchorBottom && this.scrollToAnchorBottom('auto')

      const [err, response] = await conversation(params)

      if (err !== null || response === null) {
        this.setStatus('error')
        this.curNode.status = 'error'
        return
      }
      this.setStatus('chating')
      const stream = response.body?.getReader()
      const { status, message_id, errorCode, errorInfo } = await queueReponseText.readStream(stream, this.curNode)

      this.setStatus(status, errorCode)
      if (status === 'error') {
        this.toastErrors(errorCode, this.getCurrentModel())
        this.curNode.errorCode = errorCode
        this.curNode.errorInfo = errorInfo
        return
      }
      if (isNewConverSation) {
        this.$store.dispatch('history/addHistory', { item: message, conversionId, response: this.curNode?.target?.content || '' })
      }
      if (message_id) this.$store.dispatch('chat/setToCacheItem', this.curNode)
      await this.updateUserToken()

      if (this.userInfo.userToken < process.env.VUE_APP_MIN_COUNT) {
        this.toastErrors(1008, null)
      }
    },
    /**
   * 重新生成消息
   * @return
   */
    // eslint-disable-next-line sonarjs/cognitive-complexity
    async resendMessage () {
      if (!this.detechRightsRest()) return
      this.$store.dispatch('chat/setChatStore', { isChating: true })

      let messages = getResendMessageList(this.rootNode) // fix: 不可传入this.curNode，在历史记录操作重新生成会导致历史记录的上下文错位问题
      // 重新生成不需要最后一条消息
      if (this.chatStore.status !== 'error' && this.chatStore.docSummarize.status !== 'error') {
        messages.pop()
      }
      // fix: 发生错误时，重新生成不带用户当前消息问题
      const currUserMessages = getResendMessageList(null, this.curNode)[0]
      if (currUserMessages && !messages.some(({ message_id }) => message_id === currUserMessages.message_id)) {
        messages.push(currUserMessages)
      }
      if (messages.slice(-1)[0].business === '1') {
        messages = messages.slice(-1)
      }
      const conversionId = this.chatStore.conversionId
      const docSummarize = this.chatStore.docSummarize
      const params = getSendParams(
        messages,
        this.getCurrentModel(),
        conversionId,
        docSummarize.document?.knowledge_id
      )

      params.enable_tool_serper = this.chatStore.onlineSwitch

      if (this.chatStore.agent) {
        this.$xz('HtmlClickReport', { ReportID: 7621 })
        params.app_assistant_id = this.chatStore.agent.id
      }
      if (messages[0].business === '1') { // 待办优先级最高
        params.app_assistant_id = 489
      }
      // 移除链表最后一个节点
      const old = this.popListChain()

      await awaitNextick()

      this.addServerItem(getPrevValidateCode(this.curNode, 'assistant')?.message_id || '', params.app_assistant_id === 489 ? '1' : null)
      this.$store.dispatch('chat/setChatStore', { newSession: this.chatStore.newSession + 1 })
      this.setStatus('wait')
      this.curNode.status = 'wait'
      this.$xz('HtmlClickReport', { ReportID: 7615 })
      const [err, response] = await conversation(params)
      this.setStatus('chating')
      if (err !== null || response === null) {
        this.setStatus('error')
        this.curNode.status = 'error'
        return
      }
      const stream = response.body?.getReader()
      const { status, message_id, errorCode, errorInfo } = await queueReponseText.readStream(stream, this.curNode)
      this.setStatus(status, errorCode)
      if (status === 'error') {
        this.toastErrors(errorCode, this.getCurrentModel())
        this.curNode.errorCode = errorCode
        this.curNode.errorInfo = errorInfo
        return
      }
      if (params.app_assistant_id === 489) {
        this.curNode.target.business = '1'
      }
      this.$store.dispatch('chat/setToCacheItem', this.curNode)
      if (old) this.$store.dispatch('chat/updateNodesBrothers', { old, message_id })
      await this.updateUserToken()

      if (this.userInfo.userToken < process.env.VUE_APP_MIN_COUNT) {
        this.toastErrors(1008, null)
      }
    },

    /**
   * 停止会话消息
   * @return
   */
    async stopMessage () {
      const conversionId = this.chatStore.conversionId
      const target = this.curNode
      const messageId = target.message_id
      const { data } = await conversationStop(conversionId, messageId)
      if (data?.code === 200) {
        queueReponseText.stop()
        this.setStatus('stop')
        return
      }
      PsMessage({ message: '请稍候重试或联系客服' })
    },

    // 添加新会话
    async addNewMessage (value) {
      // debugger
      if (['chating'].includes(this.chatStore.status)) {
        PsMessage({ message: '正在生成，请稍等！' })
        return
      }
      queueReponseText.destroy()
      await awaitNextick()
      this.resetNode()
      // eslint-disable-next-line sonarjs/no-duplicate-string
      this.$store.dispatch('chat/reset')
      this.$store.dispatch('chat/resetDocumentSummarize')
      if (value) {
        if (!this.detechRightsRest()) return
        this.$store.dispatch('chat/setChatStore', { isChating: true })
        this.sendMessage(value)
      }
    },

    // 重置会话
    resetNode () {
      this.rootNode = null
      this.curNode = null
    },
    /**
   * 切换消息
   * @return
   */
    async switchMessage (node, type) {
      const index = node?.renderIndex
      const len = node.brothers.length
      const will = type === 'prev' ? index - 1 : index + 1
      if (will < 0 || will >= len) return

      this.swtichMessage(node, will)
    },

    async  setNewChatToInput (value) {
      if (['chating'].includes(this.chatStore.status)) return
      queueReponseText.destroy()
      this.resetNode()
      this.$store.dispatch('chat/reset')
      this.$store.dispatch('chat/setChatStore', { chatInput: value })
      await awaitNextick(0.3)
    },

    // 获取历史记录最后一条会话使用的模型
    settHisotryLastMessageModel (item, messages) {
      const isDocSummarize = !!item.knowledge?.knowledge_id
      if (isDocSummarize) {
        const modelTitle = item.knowledge?.knowledge_type
        const target = this.chatStore.documentModels.find(
          (v) => v.name === modelTitle || v.model === modelTitle
        )

        if (target) {
          // eslint-disable-next-line sonarjs/no-duplicate-string
          this.$store.dispatch('chat/setCurrentModel', { model: target, type: 'doc' })
          // eslint-disable-next-line sonarjs/no-duplicate-string
          this.$store.dispatch('chat/setDocSummarize', {
            documentModel: modelTitle,
            documentModelName: target.name
          })
        }
      }
      if (messages?.length) {
        const lastMessage = messages[messages.length - 1]
        const target = this.chatStore.models.find(
          (v) => v.name === lastMessage.model_title
        )
        if (target) this.$store.dispatch('chat/setCurrentModel', { model: target })
      }
      return null
    },

    // 读取历史对话
    // eslint-disable-next-line sonarjs/cognitive-complexity
    async setHistoryMessage (item) {
      const self = this
      await awaitNextick(0.2)

      const document_id = item.knowledge?.documents[0]?.document_id
      const knowledge_id = item.knowledge?.knowledge_id

      // 获取文档详情
      if (document_id) {
        const promiseList = [getDocumentSummary(knowledge_id, document_id)]
        promiseList.push(getDocumentSuggestion(knowledge_id))
        const [docData, question] = await Promise.all(promiseList)
        const { data: doc } = docData

        if (doc?.code !== 200) {
          PsMessage({ message: '请稍候重试或联系客服' })
          return
        }
        this.resetNode()
        this.$store.dispatch('chat/reset')
        // eslint-disable-next-line sonarjs/no-duplicate-string
        this.$store.dispatch('chat/setDocSummarize', {
          documentModel: item.knowledge?.knowledge_type || '',
          documentModelName: ''
        })
        this.$store.dispatch('chat/setDocumentSummarize', { status: 'end', type: formatSumarizeType(doc.data), data: doc.data })
        const targetModel = this.chatStore.documentModels?.find(
          (v) => v.model === item.knowledge?.knowledge_type
        )
        if (targetModel) {
          this.$store.dispatch('chat/setCurrentModel', { model: targetModel, type: 'doc' })
          this.$store.dispatch('chat/setDocSummarize', {
            documentModel: targetModel?.model || '',
            documentModelName: targetModel?.name || ''
          })
        }
        // 更新问题列表
        if (question) {
          this.$store.dispatch('chat/setDocSummarize', {
            questions: question.data?.data?.suggested_questions || []
          })
        }
      } else {
        this.resetNode()
        this.$store.dispatch('chat/reset')
      }
      if (item.app_assistant_id) {
        const { data } = await getAgentDetailApi(item.app_assistant_id)
        if (data?.code !== 200) {
          PsMessage({ message: data?.msg || '服务请求错误，请稍后再试' })
          return
        }
        const assistant = data.data.app_assistant
        if (assistant.assistant?.third_detail) {
          assistant.assistant.third_detail = JSON.parse(assistant.assistant.third_detail)
        }
        this.$store.dispatch('chat/setChatStore', { agent: assistant })
      }
      const { data } = await getConversationMessages(item.conversation_id)
      this.settHisotryLastMessageModel(item, data?.messages)
      if (data?.code === 200) {
        this.$store.dispatch('chat/setHistoryMessage', {
          messages: data.messages || [],
          conversation_id: item.conversation_id,
          callback: function (root, cur) {
            self.rootNode = root
            self.curNode = cur
          }
        })
      }
    },

    // 重新编辑信息
    async reEditMessage () {
      const curNode = this.curNode
      const prev = getPrevValidateCode(curNode, 'user')
      const newNode = prev.prev
      if (!newNode && this.chatStore.agent === null && !this.isDocSummarize()) {
      // 如果为第一条信息，跳回首页
        this.setNewChatToInput(prev.target?.content || '')
        return
      }
      const message_id = getSnowflakeId()
      const tipsNode = {
        root: false,
        prev: newNode,
        next: null,
        message_id: message_id,
        parent_message_id: newNode.message_id,
        role: 'tips',
        target: {
          role: 'tips',
          message_id: message_id,
          parent_message_id: newNode.message_id,
          content: '您重新编辑了一个问题'
        },
        brothers: []
      }
      newNode.next = tipsNode
      this.setStatus('end')
      this.curNode = tipsNode
      this.$store.dispatch('chat/setChatStore', { chatInput: prev.target?.content || '' })
    },
    // 添加粘贴板节点
    addClipbordTipsNode (msg) {
    // 网页总结暂不支持对话
    // if (isLinkSummarize()) {
    //   return
    // }
      const message_id = getSnowflakeId()
      const clipboardNode = {
        root: false,
        prev: null,
        next: null,
        message_id: message_id,
        parent_message_id: '',
        role: 'clipbord',
        target: {
          content: msg,
          role: 'clipbord',
          message_id: message_id,
          parent_message_id: ''
        },
        brothers: []
      }
      if (this.curNode?.role === 'clipbord') {
        if (this.curNode.target) this.curNode.target.content = msg
        return
      }
      if (!this.rootNode || this.curNode?.root) {
        clipboardNode.root = true
        this.rootNode = clipboardNode
        this.curNode = clipboardNode
        return
      }
      clipboardNode.prev = this.curNode
      if (this.curNode) this.curNode.next = clipboardNode
      this.curNode = clipboardNode
    },

    removeClipbordTipsNode (force) {
      if (this.curNode?.role === 'clipbord') {
        if (this.curNode.root) {
          if (force && !this.isDocSummarize()) {
            this.resetNode()
            this.$store.dispatch('chat/reset')
            return
          }
          this.rootNode = null
          return
        }
        const prev = this.curNode?.prev
        if (prev) {
          this.$store.dispatch('chat/setChatStoreCurN', { ...prev, next: null })
        }
      }
    },

    // 点击获取智能体详情
    async clickAgentItem (item, noFromHome) {
      this.$xz('HtmlClickReport', { ReportID: 7620 })
      if (noFromHome) {
        this.$store.dispatch('agent/setNoFromHome', true)
        this.$store.dispatch('chat/setChatStore', { prevConversionId: this.chatStore.conversionId || '' })
      }
      const { data } = await getAgentDetailApi(item.id || item.agent_id)
      if (data?.code === 200 && data?.data.app_assistant) {
        const assistant = data.data.app_assistant
        if (assistant.assistant?.third_detail) {
          assistant.assistant.third_detail = JSON.parse(assistant.assistant.third_detail)
        }

        const model = assistant.assistant?.third_detail?.model_config?.model || {}
        const curModel = this.chatStore.models.find((v) => v.model === model.name)
        if (curModel) this.$store.dispatch('chat/setCurrentModel', { model: curModel })
        this.resetNode()
        this.$store.dispatch('chat/reset')
        this.$store.dispatch('agent/setAgentShow', false)
        this.$store.dispatch('chat/setChatStore', { isChating: true, showModels: false, agent: assistant })
        return
      }
      PsMessage({ message: data?.msg || '服务请求错误，请稍后再试' })
    },
    updateUserToken () {
      this.$xz('BroadcastData', 'aichat:onAiTokenChange')
      return this.$store.dispatch('user/getUserRights')
    }
  }
}
